import Vue from 'vue'
import VueRouter from 'vue-router'
import ProductManagement from '../views/ProductManagement.vue'
import ProductDetail from '../views/ProductDetail.vue'
import AboutView from '../views/AboutView.vue'
import QualificationAudit from '../views/QualificationAudit.vue'
import QualificationSubmit from '../views/QualificationSubmit.vue'
import OrderManagement from '../views/OrderManagement.vue'
import LoginPage from '../views/login.vue'
import ProductAttribute from '../views/ProductAttribute.vue'
import BillingManagement from '../views/BillingManagement.vue'
import CouponManagement from '../views/CouponManagement.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginPage
  },
  {
    path: '/productManagement',
    name: 'productManagement',
    meta: { requiresAuth: true },
    component: ProductManagement
  },
  {
    path: '/product/detail/:id',
    name: 'productDetail',
    component: ProductDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView,
    meta: { requiresAuth: true }
  },
  { path: '/qualification-audit',
    name: 'qualificationAudit',
    component: QualificationAudit,
    meta: { requiresAuth: true }
  },
  { path: '/qualification-submit',
    name: 'qualificationSubmit',
    component: QualificationSubmit,
    meta: { requiresAuth: true }
  },
  {
    path: '/order-management',
    name: 'orderManagement',
    component: OrderManagement,
    meta: { requiresAuth: true }
  },
  { path: '/product-attribute',
    name: 'productAttribute',
    component: ProductAttribute,
    meta: { requiresAuth: true }
  },
  { path: '/billing',
    name: 'billingManagement',
    component: BillingManagement,
    meta: { requiresAuth: true }
  },
  { path: '/coupon-management',
    name: 'couponManagement',
    component: CouponManagement,
    meta: { requiresAuth: true }
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否有token
  const token = localStorage.getItem('token');
  if (!token) {
    // 没有token，重定向到登录页
    // 避免循环重定向
    if (to.path === '/login') {
      next();
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    }
  } else {
    // 有token，继续访问
    next();
  }
})

export default router
